<?php

/*MuseFrame*/

namespace App\Tools;

use App\Tools\Curl;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class MuseFrame {
	private $config;

	public $tableName = "af_event_log";

	public function __construct() {
		$this->config = [
			'apiHost' => 'http://47.236.118.94:7860/museframe/submit/createVideo'
		];
	}

	

	//文生视频
	public function addTask($motion, $prompt, $proportion, $videoDuration, $videoQuantity) {
		$headers = array();
		$headers[] = "Content-Type:application/json";
		$taskId = $this->generateTaskId();
		$params = [
			'motion' => $motion, 'prompt' => $prompt,
			'proportion' => $proportion, 'videoDuration' => $videoDuration,
			'videoQuantity' => $videoQuantity, 'taskId' => $taskId
		];

		$curl = new Curl();
		$result = $curl->curl_request($this->config['apiHost'], $params, 'json', 'POST', $headers);

		$id = $this->addData($data);//加入task_img任务表

		Log::info('MuseFrameLog', [
			'params' => $params, 'result' => $result
		]);

		return $result;
	}


	/**
	 * @desc  添加生成图片的任务
	 * @return string
	 * */
	public function addTaskBak($data) {

		$postData = [];
		$postData['task_id'] = $data['task_id'] ?? '';
		$postData['model'] = $data['model'] ?? '';
		$postData['type'] = $data['type'] ?? 1;
		$postData['prompt'] = $data['prompt'] ?? '';
		$postData['negative_prompt'] = $data['negative_prompt'] ?? '';
		$postData['drawing_url'] = $data['drawing_url'] ?? '';
		$postData['width'] = $data['width'] ?? 512;
		$postData['height'] = $data['height'] ?? 768;
		$postData['is_high'] = $data['is_high'] == 1 ? 'y' : 'n';
		$postData['translate'] = 'y';//是否翻译
		$postData['filter_sensitive'] = 'n';//是否过滤敏感词
		$postData['img_validate'] = 'n'; //是否鉴黄
		$data['translate'] = $postData['translate'];
		$data['filter_sensitive'] = $postData['filter_sensitive'];
		$data['img_validate'] = $postData['img_validate'];
		$isVip = $this->userIsVip($data['user_id']);
		$isTry = $isVip == true ? 2 : 1;
		$data['is_try'] = $isTry;

		if (isset($data['special']) && $data['special'] == 1) {//特殊逻辑，不扣点数
			$data['dot'] = 0;
		}else{
			$data['dot'] = $data['is_high'] == 1 ? FunTool::getHighDrawingDot() : 0;
		}
		if (1 == FunTool::getPlatform() && in_array($postData['type'], [1,2])) {//IOS文生图
			$postData['clothing_adjuster'] = -1;
			$postData['img_validate'] = 'y';
			$postData['filter_sensitive'] = 'y';
		}
		$id = $this->addData($data);//加入task_img任务表
		$headers = [];
		$headers[] = "KEY:".$this->config['app_key'];

		$curl = new Curl();
		$result = $curl->curl_request($this->config['apiHost'], $postData, 'urlencoded', 'POST', $headers);
		if (empty($result) || !isset($result['code']) || $result['code']!=200) {
			$result = $curl->curl_request($this->config['apiHost'], $postData, 'urlencoded', 'POST', $headers);
		}
		$retData = [
            'status' => 0,
            'url' => '',
            'size' => 1,
            'index' => 1,
            'time' => 8,
            'task_id' => $data['task_id'],
            'refresh_uri' => '/v2/opus/task?task_id=' . $data['task_id'],
            'refresh_time' => 5,
            'prompt' => $data['prompt'],
            'type' => $data['type'],
            'negative_prompt' => $data['negative_prompt'],
            'height' => $data['height'],
            'width' => $data['width'],
            'model_id' => intval($data['model_id']),
            'is_high' => $data['is_high'],
            'prepare_id'=>$data['prepare_id']
        ];

        if (!empty($task_info['extend'])) {
        	$extend = json_decode($task_info['extend']);
        }else{
        	$extend = [];
        }
        $extend['task_loading'] = $retData;

        DB::table('task_img')->where('id',$id)->update(['revert'=>json_encode($result),'extend'=>json_encode($extend)]);

		return $retData;
	}

	/**
	 * 写入task_img任务表
	 */
	public function addData($data) {	
		$aData = [];
		$aData['task_id'] = $data['task_id'] ?? '';
		$aData['user_id'] = $data['user_id'] ?? 0;
		$aData['model_id'] = $data['model_id'] ?? 0;
		$aData['model'] = $data['model'] ?? '';
		$aData['type'] = $data['type'] ?? 1;
		$aData['prompt'] = $data['prompt'] ?? '';
		$aData['negative_prompt'] = $data['negative_prompt'] ?? '';
		$aData['drawing_url'] = $data['drawing_url'] ?? '';
		$aData['width'] = $data['width'];
		$aData['height'] = $data['height'];
		$aData['is_high'] = $data['is_high'] ?? 0;
		$aData['translate'] = $data['translate'] == 'y' ? 1 : 2;
		$aData['filter_sensitive'] = $data['filter_sensitive'] == 'y' ? 1 : 2;
		$aData['img_validate'] = $data['img_validate'] == 'y' ? 1 : 2;
		$aData['style_id'] = $data['style_id'] ?? 0;
		$aData['prepare_id'] = $data['prepare_id'] ?? 0;
		$aData['is_try'] = $data['is_try'];
		$aData['device_id'] = FunTool::getDeviceId();
		$aData['dot'] = $data['dot'];
		$aData['platform'] = FunTool::getPlatform() ?? 0;
		$aData['machine_id'] = $data['machine_id'] ?? '';
		$aData['is_style_orginal'] = $data['is_style_orginal'] ?? 0;
		$aData['created_at'] = FunTool::getCurrentTime();
		$now = strtotime(FunTool::getCurrentTime()) + $this->config['task_expire'];
		$aData['expire_time'] = date('Y-m-d H:i:s', $now);

		$id = DB::table('task_img')->insertGetId($aData);
		
		return $id;
	}

	/**
	 * 作图中心回调接口
	 */
	public function webHooks($data){

		$task_id = $data['task_id'];
		$task_info = DB::table('task_img')->where('task_id',$task_id)->first();
		if (empty($task_info)) {
			return ['code'=>500, 'msg'=>'任务信息为空'];
		}
		$task_info = (array)$task_info;
		$img_url = $data['img_url'] ?? '';
		$img_thumb_url = $data['img_thumb_url'] ?? '';
		$status = $data['status'];
		$is_nsfw = isset($data['is_nsfw']) && $data['is_nsfw'] == 'y' ? 'y' : 'n';
		$isNsfw = $is_nsfw == 'y' ? 1 : 2;
		$prompt_use = $data['prompt_use'] ?? '';
		$validate_status = $data['validate_status'] ?? '';

		$insertData = [];
		$insertData['task_id'] = $task_id;
		$insertData['user_id'] = $task_info['user_id'];
		$insertData['prompt'] = $task_info['prompt'];
		$insertData['prompt_use'] = $prompt_use;
		// $insertData['device_id'] = $task_info['device_id'];
		$insertData['url'] = $img_url;
		$insertData['created_at'] = FunTool::getCurrentTime();
		// $insertData['title'] = $task_info['prompt'];
		// $insertData['width'] = $task_info['width'];
		// $insertData['height'] = $task_info['height'];
		// $insertData['dot'] = $task_info['dot'];
		// $insertData['negative_prompt'] = $task_info['negative_prompt'];
		$insertData['type'] = $task_info['type'];
		// $insertData['use_dot'] = $task_info['dot'];
		// $insertData['drawing_id'] = $task_info['model_id'];
		// $insertData['drawing_image'] = $task_info['drawing_url'];
		// $insertData['is_try'] = $task_info['is_try'];
		// $insertData['style_id'] = $task_info['style_id'];
		// $insertData['is_style_orginal'] = $task_info['is_style_orginal'];
		// $insertData['platform'] = $task_info['platform'];
		// $insertData['machine_id'] = $task_info['machine_id'];
		// $insertData['prepare_id'] = $task_info['prepare_id'];
		//$insertData['thumb_url'] = $img_thumb_url;
		$insertData['is_high'] = $task_info['is_high'];
		//$insertData['nsfw'] = $isNsfw;

		if ('success' == $status) {
			if ($data['validate_status'] == 'fail' ) {//鉴黄不通过
				$new_url = $this->jianHuang($task_info);
				if (!empty($new_url)) {
					$insertData['url'] = $new_url;
				}
			}
			$res = DB::table('opus')->insertGetId($insertData);
			$task_extend = json_decode($task_info['extend'], true);
			$task_extend['success_img_url'] = $img_url;
			$task_extend['success_img_thumb_url'] = $img_thumb_url;
			$task_extend['task_loading']['status'] = 2;//2的时候，端上跳转到结果页
			$task_extend['task_loading']['url'] = $img_url;
			DB::table('task_img')->where('id',$task_info['id'])->update([
				'status'=>1, 
				'webhooks'=>json_encode($data),
				'extend'=>json_encode($task_extend)
			]);

		}else{
			DB::table('task_img')->where('id',$task_info['id'])->update([
				'status'=>2, 
				'webhooks'=>json_encode($data)
			]);
			// if ($task_info['dot'] > 0 && $task_info['user_id']>0) {//制作失败，返回点数
			// 	DB::table('user')->where('id',$task_info['user_id'])->increment('dot',$task_info['dot']);
			// }
		}

		return ['code'=>200, 'msg'=>'ok'];

	}
}
